//用js实现reduce方法
// 定义一个数组的自定义reduce方法
Array.prototype.myReduce = function(callback, initialValue) {
    let accumulator = initialValue;
    let startIndex = 0;
    // 如果没有提供初始值，将数组的第一个元素作为累加器的初始值
    if (initialValue === undefined) {
        accumulator = arr[0];
        startIndex = 1;
    }
    // 遍历数组
    for (let i = startIndex; i < this.length; i++) {
        // 调用回调函数，更新累加器
        accumulator = callback(accumulator, arr[i], i, arr);
    }
    return accumulator;
};

// 测试示例
const arr = [1, 2, 3, 4];
const sum = arr.myReduce((acc, current) => acc + current, 0);
console.log(sum);